﻿/* Serialize Plugin Context
 * Copyright Andrew Swerlick - Engage, Inc. 2010
 * is free software: you can redistribute it and/or modify it under the terms of the 
 * GNU General Public License as published by the Free Software Foundation, 
 * either version 3 of the License, or (at your option) any later version.
 * Serialize Plug-in Context is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; 
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
 * See the GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License along with Serialize Plug-in Context. 
 * If not, see http://www.gnu.org/licenses/.
 ***********************************************/

using System;
using Microsoft.Xrm.Sdk;
using System.Runtime.Serialization;
using System.IO;

namespace SerializePluginContext
{
    /// <summary>
    /// A plug-in that takes the IServiceProvider object passed to it, get's the IPluginExecutionContext, and then serializes it to create an xml file 
    /// that can be easily deserialized for testing using the Engage.Util.PluginTester in the PluginTester assembly. The file is copied to 
    /// C:\windows\temp\[PrimaryEntityName]-[MessageName][UniqueNumber] on the CRM server after the plug-in has been executed
    /// </summary>
    public class SerializingPlugin : IPlugin
    {

        #region IPlugin Members

        public void Execute(IServiceProvider serviceProvider)
        {
            #region Serialize Context
            // Get the context
            var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

            // Get the known types
            var knownTypes = new[] {typeof (Entity)};
            var contextFormatter = new DataContractSerializer(typeof(MyPluginContext), knownTypes);

            // Copy the context to MyPluginContext (myContext)
            var myContext = MyPluginContext.Copy(context);

            // Setup the filename
            var filename = string.Format(@"C:\windows\temp\{0}-{1}", context.PrimaryEntityName, context.MessageName);
            const string extension = ".xml";
            int i = 1;

            var suffix = String.Format("-{0:000}", i);
            while (File.Exists(filename + suffix + extension))
            {
                suffix = String.Format("-{0:000}", ++i);
            }

            // Create the file
            var file = File.Create(filename + suffix + extension);

            // Write the XML to the file
            contextFormatter.WriteObject(file, myContext);
            file.Flush();
            file.Close();

            #endregion
        }

        #endregion
    }
}
